<template>
  <div class="flex flex-col" :style="{ height }">
    <!-- 工具栏 -->
    <vxe-toolbar v-if="showToolbar" class="flex-shrink-0">
      <template #buttons>
        <slot name="toolbar-left" />
      </template>
      <template #tools>
        <slot name="toolbar-right" />
      </template>
    </vxe-toolbar>

    <!-- 表格 -->
    <vxe-table
      ref="xTable"
      class="flex-1"  
      :stripe="stripe"
      :row-class-name="rowClassName"    
      :data="tableData"
      :loading="loading"
      :row-config="{ isHover: true,  keyField: rowKey }"
      :column-config="{ resizable: true }"
      :sort-config="sortConfig"
      :checkbox-config="checkboxConfig"
      :edit-config="editConfig"
      @checkbox-change="handleSelectionChange"
      @checkbox-all="handleSelectionChange"
      @cell-dblclick="handleCellDbClick"   
      @row-dblclick="handleRowDbClick"
      @row-click="handleRowClick"
      @cell-click="handleCellClick"       
      @sort-change="handleSortChange"
    >
      <!-- 动态列 -->
      <vxe-column
        v-for="col in processedColumns"
        :key="col.field"
        :type="col.type"
        :field="col.field"
        :title="col.title"
        :width="col.width"
        :min-width="col.minWidth"
        :fixed="col.fixed"
        :sortable="col.sortable"
        :filters="col.filters"
        :filter-method="col.filterMethod"
        :edit-render="col.editRender"
        :show-overflow="col.showOverflow"
      >
        <!-- 自定义单元格 -->
        <template v-if="$slots[col.field]" #default="{ row }">
          <slot :name="col.field" :row="row" />
        </template>
      </vxe-column>

      <!-- 右侧操作列（可选） -->
      <vxe-column
        v-if="$slots.operate"
        title="操作"
        fixed="right"
        :width="operateWidth"
      >
        <template #default="{ row }">
          <slot name="operate" :row="row" />
        </template>
      </vxe-column>
    </vxe-table>

    <!-- 分页 -->
    <vxe-pager
      v-if="showPager"
      class="flex-shrink-0"
      :current-page="innerPage.currentPage"
      :page-size="innerPage.pageSize"
      :total="innerPage.total"
      :page-sizes="innerPage.pageSizes"
      :layouts="pagerLayouts"
      @page-change="onPageChange"
    />
  </div>
</template>

<script setup lang="ts">
import type { PropType } from 'vue'
import { ref, reactive, computed, watch } from 'vue'
import zhCN from 'vxe-table/lib/locale/lang/zh-CN'
import enUS from 'vxe-table/lib/locale/lang/en-US'


import type {
  VxeTableInstance,
  VxeTablePropTypes,  
  VxeTableEvents
} from 'vxe-table'

import type { VxePagerEvents, VxePagerPropTypes } from 'vxe-pc-ui'
// 使用
import type { VxeTableDefines } from 'vxe-table'
import defaultConfig from '@config/index.js'; // 相对路径






const filterAgeMethod: VxeTablePropTypes.FilterMethod = ({ value, row }) => {
  // your filter logic
}
/* -------------------- 类型 -------------------- */
export interface PageInfo {
  currentPage: number
  pageSize: number
  pageSizes: number[]
  total: number
}

export interface Column {
  field: string
  title: string
  type?: 'seq' | 'checkbox' | 'radio'
  width?: number | string
  minWidth?: number | string
  fixed?: 'left' | 'right'
  sortable?: boolean
  filters?: any[]
  filterMethod?: VxeTablePropTypes.FilterMethod
  editRender?: any
  showOverflow?: boolean
  is_filter?: boolean
}

/* -------------------- Props -------------------- */
const props = defineProps({
  /* 必填 */
  tableColumns: { type: Array as PropType<Column[]>, required: true },
  tableData: { type: Array as PropType<any[]>, default: () => [] },
  fullData: { type: Array as PropType<any[]>, default: () => [] }, // 完整数据源用于生成过滤选项
  /* 分页 */
  page: { type: Object , default: () => ({ currentPage: defaultConfig.tableCurrentPage, 
                                              pageSize: defaultConfig.tablePageSize, 
                                              total: 0,
                                              pageSizes:defaultConfig.tablePageSizes }) },
  // pageSizes: { type: Array as PropType<number[]>, default: () => [10, 20, 50, 100] },
   // pagerLayouts: { type: Array as PropType<string[]>, default: () => ['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total'] },
 
  pagerLayouts: { 
    type: Array as PropType<VxePagerPropTypes.Layouts>, 
    default: () => ['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total'] 
  },
 
  showPager: { type: Boolean, default: true },
  /* 外观 */
  height: { type: String, default: '600px' },
  showToolbar: { type: Boolean, default: true },
  operateWidth: { type: Number, default: 120 },
  rowKey: { type: String, default: 'id' },
  loading: { type: Boolean, default: false },
  stripe: { type: Boolean, default: false }, // 添加 stripe 属性
  rowClassName: { type: Function as PropType<(params: any) => string>, default: undefined }, 
  /* 功能 */
  sortConfig: { type: Object as PropType<VxeTablePropTypes.SortConfig>, default: () => ({ remote: false }) }, // false :本地排序 true：远程排序
  checkboxConfig: { type: Object as PropType<VxeTablePropTypes.CheckboxConfig>, default: () => ({ highlight: true, range: true }) },
  editConfig: { type: Object as PropType<VxeTablePropTypes.EditConfig>, default: undefined }
})

const innerPage = computed(() => ({
  currentPage: defaultConfig.tableCurrentPage,
  pageSize: defaultConfig.tablePageSize,
  pageSizes: defaultConfig.tablePageSizes,
  total: 0,
  ...props.page
}))

// 添加一个计算属性来处理列配置
// 添加一个计算属性来处理列配置
const processedColumns = computed(() => {
  return props.tableColumns.map(col => {
    // 如果设置了 is_filter 且有 field 字段
    if (col.is_filter && col.field) {
      // 检查是否需要自动生成 filters（没有手动定义或者为空数组）
      const needGenerateFilters = !col.filters || col.filters.length === 0;
      
      if (needGenerateFilters) {
        // 从完整数据中提取唯一值作为过滤选项
        let filters = [];
        const dataSource = props.fullData && props.fullData.length > 0 ? props.fullData : props.tableData;
        console.log('dataSource', dataSource);
        if (dataSource && dataSource.length > 0) {
          const uniqueValues = [...new Set(dataSource.map(item => item[col.field]))];
          filters = uniqueValues
            .filter(value => value !== undefined && value !== null)
            .map(value => ({
              label: String(value),
              value: value
            }));
        }
        
        // 创建默认的过滤方法
        const defaultFilterMethod: VxeTablePropTypes.FilterMethod = ({ value, row }) => {
          if (value === null || value === undefined || value === '') {
            return true;
          }
          return row[col.field] == value;
        };
        
        return {
          ...col,
          filters: filters,
          filterMethod: defaultFilterMethod
        };
      }
    }
    return col;
  });
});
/* -------------------- Emits -------------------- */
const emit = defineEmits([
  'update:page',
  'selection-change',
  'sort-change',
  'row-dblclick',       
  'cell-dblclick',      
  'row-click',          
  'cell-click'          
])

/* -------------------- 事件 -------------------- */
const xTable = ref<VxeTableInstance>()

const onPageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
  emit('update:page', { ...props.page, currentPage, pageSize })
}


const handleSelectionChange: VxeTableEvents.CheckboxChange | VxeTableEvents.CheckboxAll = () => {
  console.log('选中的行数:')
  const records = xTable.value?.getCheckboxRecords() ?? []
  console.log('选中的行:', records)
  emit('selection-change', records)
}
const handleCellDbClick: VxeTableEvents.CellDblclick = ({ row, column, cell, $event }) => {
  emit('cell-dblclick', row, column, cell, $event);
}

const handleRowClick = ({ row, $event }) => {
  emit('row-click', row, $event);
}
const handleRowDbClick: any = ({ row, $event }) => {
  emit('row-dblclick', row, $event);
}
const handleCellClick: VxeTableEvents.CellClick = ({ row, column, cell, $event }) => {
  emit('cell-click', row, column, cell, $event);
}


const handleSortChange: VxeTableEvents.SortChange = (params) => {
  console.log('排序参数:', params)
  emit('sort-change', params)
}

/* -------------------- 暴露 -------------------- */
defineExpose({
  getTableRef: () => xTable.value,
  getCheckboxRecords: () => xTable.value?.getCheckboxRecords() ?? [],
  clearCheckboxRow: () => xTable.value?.clearCheckboxRow()
})
</script>
